package com.picshare.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.picshare.model.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserService {
    
    @Value("${app.data.dir}")
    private String dataDir;
    
    @Value("${app.default.username}")
    private String defaultUsername;
    
    @Value("${app.default.password}")
    private String defaultPassword;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    private File userFile;
    private Map<String, User> users = new HashMap<>();
    
    @PostConstruct
    public void init() {
        createDataDirectory();
        userFile = new File(dataDir, "users.json");
        loadUsers();
        createDefaultUser();
    }
    
    private void createDataDirectory() {
        try {
            Files.createDirectories(Paths.get(dataDir));
        } catch (IOException e) {
            System.err.println("创建数据目录失败: " + e.getMessage());
        }
    }
    
    private void loadUsers() {
        if (userFile.exists()) {
            try {
                User[] userArray = objectMapper.readValue(userFile, User[].class);
                for (User user : userArray) {
                    users.put(user.getUsername(), user);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    private void saveUsers() {
        try {
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(userFile, users.values().toArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private void createDefaultUser() {
        if (!users.containsKey(defaultUsername)) {
            User defaultUser = new User();
            defaultUser.setUsername(defaultUsername);
            defaultUser.setPassword(encodePassword(defaultPassword));
            defaultUser.setNickname("管理员");
            defaultUser.setCreatedAt(System.currentTimeMillis());
            users.put(defaultUsername, defaultUser);
            saveUsers();
        }
    }
    
    public User login(String username, String password) {
        User user = users.get(username);
        if (user != null && user.getPassword().equals(encodePassword(password))) {
            return user;
        }
        return null;
    }
    
    public boolean changePassword(String username, String oldPassword, String newPassword) {
        User user = users.get(username);
        if (user != null && user.getPassword().equals(encodePassword(oldPassword))) {
            user.setPassword(encodePassword(newPassword));
            saveUsers();
            return true;
        }
        return false;
    }
    
    private String encodePassword(String password) {
        return UUID.nameUUIDFromBytes(password.getBytes()).toString();
    }
}